package com.security.activity;

import android.app.AlertDialog;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.os.Looper;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;

import org.json.JSONObject;

import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainVM extends AndroidViewModel {
    Context context;
    MutableLiveData<String> account,password;
    public TextWatcher accountWatcher=new TextWatcher(){
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            account.setValue(s.toString());
            Toast.makeText(context,s.toString(),Toast.LENGTH_SHORT).show();
        }
        @Override
        public void afterTextChanged(Editable s) {
        }
    };
    public TextWatcher passwordWatcher=new TextWatcher(){
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            password.setValue(s.toString());
        }
        @Override
        public void afterTextChanged(Editable s) { }
    };
    public MainVM(@NonNull Application application) {
        super(application);
        context=application;
        if (account==null){
            account=new MutableLiveData<>();
        }
        if (password==null){
            password=new MutableLiveData<>();
        }
        account.setValue("");
        password.setValue("");
    }


    public void login(View view){
        final Request.Builder builder=new Request.Builder().url("https://api2.bmob.cn/1/login?username="+account.getValue()+"&password="+password.getValue());
        builder.addHeader("X-Bmob-Application-Id","a0e84e21a8ae973db9c1388a990533f8");
        builder.addHeader("X-Bmob-REST-API-Key","c97d9ff0b1c23e4e5749b04d963ab041");
        builder.addHeader("Content-Type","application/json");
        final Request request=builder.build();
        final OkHttpClient client=new OkHttpClient.Builder().readTimeout(30, TimeUnit.SECONDS).connectTimeout(10,TimeUnit.SECONDS).writeTimeout(60,TimeUnit.SECONDS).build();
        final Call call=client.newCall(request);
        new Thread(() -> {
            try {
                Response res = call.execute();
                if (res.code()==200){
                    context.startActivity(new Intent(context,HomeActivity.class));
                    //怎么关闭啊啊啊
                }else {
                    Looper.prepare();
                    Toast.makeText(context,"登录失败，请检查",Toast.LENGTH_LONG).show();
                    Looper.loop();
                }
            }catch (Exception e){
                Looper.prepare();
                Toast.makeText(context,"登录失败，请检查",Toast.LENGTH_LONG).show();
                Looper.loop();
            }
        }).start();
    }

    public void sign(View view) {
        context.startActivity(new Intent(context,SignActivity.class));
    }
    public void findPassword(View view) {
        EditText ed=new EditText(context);
        ed.setHint("请输入邮箱");
        AlertDialog.Builder dialog=new AlertDialog.Builder(context);
        dialog.setTitle("找回密码-发送改密邮件");
        dialog.setView(ed);
        dialog.setPositiveButton("确定", (dialogInterface, i) -> new Thread() {
            @Override
            public void run() {
                MediaType JSON = MediaType.parse("application/json;charset=utf-8");
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("email",ed.getText().toString());
                    RequestBody requestBody = RequestBody.create(JSON, String.valueOf(jsonObject));
                    Request.Builder request = new Request.Builder().url("https://api2.bmob.cn/1/requestPasswordReset");
                    request.addHeader("X-Bmob-Application-Id","a0e84e21a8ae973db9c1388a990533f8");
                    request.addHeader("X-Bmob-REST-API-Key","c97d9ff0b1c23e4e5749b04d963ab041");
                    request.addHeader("Content-Type","application/json");
                    request.post(requestBody);
                    final OkHttpClient client=new OkHttpClient.Builder().readTimeout(30, TimeUnit.SECONDS).connectTimeout(10,TimeUnit.SECONDS).writeTimeout(60,TimeUnit.SECONDS).build();
                    final Call call=client.newCall(request.build());
                    call.execute();
                    new Thread(() -> {
                        try {
                            call.execute();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start());
        dialog.setNegativeButton("取消",null);
        dialog.show();
    }


}
